package com.lagou.gateway.standard.formatter;

import com.alibaba.fastjson.JSONObject;
import com.lagou.gateway.BaseResponseBodyEntity;
import com.lagou.gateway.ResponseCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

public abstract class ResponseBodyFormatter {
    private static Logger LOGGER = LoggerFactory.getLogger(ResponseBodyFormatter.class);

    public BaseResponseBodyEntity jsonBodyFormat(HttpStatus httpStatus, String body) {
        BaseResponseBodyEntity result = new BaseResponseBodyEntity(ResponseCodeEnum.GATEWAY_ERROR, "gateway error");
        try {
            if ((body != null && body.length() >= 2)
                    && (body.charAt(0) == '{' || body.charAt(0) == '[')) {
                JSONObject object = JSONObject.parseObject(body);
                result = jsonBodyFormat(httpStatus, object);
            } else {
                result = new BaseResponseBodyEntity(ResponseCodeEnum.UNSUPPORTED_FORMAT, "body unsupported format");
            }
        } catch (Exception e) {
            LOGGER.error("Ops!Format json body error.", e);
        } finally {
            return result;
        }
    }

    public abstract BaseResponseBodyEntity jsonBodyFormat(HttpStatus httpStatus, JSONObject body);
}
